import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:yysk_app/env/env.dart';
import 'package:yysk_app/model/common_model/static_info_model.dart';
import 'package:yysk_app/model/common_model/user_info_model.dart';
import 'package:yysk_app/model/pay_model/pay_token_apply_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/net/response_data.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/pages/welcome/welcome_page.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info_plus/package_info_plus.dart';

class GlobalController extends GetxController {
  static const xPayToken = "x-pay-token";
  final payTokenDetail = Rx<dynamic?>(null);
  final user = Rx<UserInfoModel?>(null);
  final staticInfo = Rx<StaticInfoModel?>(null); //StaticInfoModel
  final headImg = ''.obs;
  //实名
  final hasAuth = false.obs;
  final version = ''.obs;
  static const uuid = 'uuid';
  //在这里用聚焦
  //判断是否聚焦
  final FocusNode focusNode = FocusNode();
  final isFocused = false.obs;
  //支付弹窗金额在使用
   var priceGet = '0'.obs;
  Timer? timer;
  @override
  Future<void> onInit() async {
    super.onInit();
    consoleLog(
      '${Env.envConfig.envName}======环境配置数据${Env.envConfig.envHttpUrl}',
    );
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    version.value = packageInfo.version;
    //当路由来自登录或者注册的时候，刷新不走这个接口适配h5
    Future.delayed(const Duration(milliseconds: 100), () {
      consoleLog('重置以后的${Get.routing.current}===========Get.routing.current');
      if (Get.routing.current.contains(LoginPage.path) ||
          Get.routing.current.contains(WelcomePage.path)) {
        getStaticData();
        //执行其他
      } else {
        getUserInfo();
        getXPayToken();
        getStaticData();
      }
    });
  }

  //获取用户信息
  getUserInfo({
    Function(ResponseData<UserInfoModel>)? success,
    Function()? fail,
  }) async {
    return await http.netFetch<UserInfoModel>(
      ApiUrl.userInfo,
      method: Method.get,
      success: (result) {
        user.value = result.data;
        hasAuth.value = result.data!.isSm!;
        saveToLocalStorage('userTel', result.data?.userTel ?? '');
        if (success != null) {
          success(result);
        }
      },
      fail: (code, message) {
        if (fail != null) {
          fail();
        }
      },
    );
  }

  Future<dynamic> updateUserInfo(Object params) async {
    final res = http.netFetch<dynamic>(
      ApiUrl.updateUserInfo,
      method: Method.post,
      params: params,
      success: (r) {
        getUserInfo();
        return r;
      },
    );
    return res;
  }

  Future<dynamic> updateInvited(Object params) async {
    consoleLog('88888888888888${params}');
    final res = http.netFetch<dynamic>(
      ApiUrl.invite,
      method: Method.post,
      params: params,
      success: (r) {
        getUserInfo();
        showToast('已绑定邀请人');
        return r;
      },
    );
    return res;
  }

  //获取凭证使用
  Future<dynamic> getXPayToken({String plat = 'USER'}) async {
    final res = http.netFetch<PayTokenApplyModel>(
      PayUrl.tokenApply,
      method: Method.post,
      params: {'plat': plat},
      success: (r) {
        if (r.code == 200) {
          payTokenDetail.value = r.data;
          saveXPayToken(r.data?.userToken);
        }
      },
    );
    return res;
  }

  //保存xPayToken
  void saveXPayToken(token) {
    HiCache.getInstance().setString(xPayToken, token);
  }

  //uuid
  void saveUuid(uuid) {
    HiCache.getInstance().setString(uuid, uuid);
  }

  //获取数据
  Future<dynamic> getStaticData() async {
    final res = http.netFetch<StaticInfoModel>(
      CommonApi.getStaticData,
      method: Method.get,
      success: (r) {
        staticInfo.value = r.data;
        return r;
      },
    );
    return res;
  }
}
